<?php

class Silk_Mapi_Model_Api2_Upgrade_Rest extends Silk_Mapi_Model_Api2_Upgrade
{
    public function _retrieve()
    {
        $appId = $this->getRequest()->getHeader('App-Id');
        if (!$appId)
            $this->_critical('缺少参数！', Mage_Api2_Model_Resource::ERROR_UNKNOWN_ERROR);

        /** @var Silk_Mapi_Model_Mysql4_Version_Collection $collection */
        $collection = Mage::getModel('mapi/version')->getCollection();
        $item = $collection
            ->addFieldToFilter('status', 1)
            ->addFieldToFilter('type', $appId)
            ->addFieldToFilter('website_ids', array('finset' => Mage::app()->getStore()->getWebsiteId()))
            ->setOrder('id', 'DESC')
            ->getFirstItem();

        if (!$item->getVersion()) {
            $this->_critical('当前版本已经是最新版本！', Mage_Api2_Model_Resource::ERROR_UPGRADE_VERSION_ALREADY_NEWEST);
        }

        if ($this->_CompareVersion($item->getVersion())) {
            return $this->_formatVersionData($item);
        }
        $this->_critical('当前版本已经是最新版本！', Mage_Api2_Model_Resource::ERROR_UPGRADE_VERSION_ALREADY_NEWEST);
    }

    protected function _CompareVersion($version)
    {
        $appVersion = $this->getRequest()->getHeader('App-Version');
        if ($appVersion && $version) {
            $appVersion = explode('.', $appVersion);
            $version = explode('.', $version);
            if (count($version)==count($appVersion) && count($appVersion) >=3) {
                $one = $version[0] > $appVersion[0];
                $two = $version[1] > $appVersion[1];
                $three = $version[2] > $appVersion[2];
                $four = $version[3] > $appVersion[3];
                $equalOne = $version[0] == $appVersion[0];
                $equalTwo = $version[1] == $appVersion[1];
                $equalThree = $version[2] == $appVersion[2];
                if ($one || ($equalOne && $two) || ($equalOne && $equalTwo && $three) || ($equalOne && $equalTwo && $equalThree && $four) ){
                    return true;
                } else{
                    return false;
                }
            }else{
                return true;
            }
            $this->_critical('版本号格式不正确', Mage_Api2_Model_Resource::ERROR_UPGRADE_VERSION_FORMAT_ERROR);
        }
        $this->_critical('缺少版本号！', Mage_Api2_Model_Resource::ERROR_UPGRADE_NO_VERSION_CODE);
    }

    protected function _formatVersionData($version)
    {
        return array(
            'version' => $version->getVersion(),
            'title' => $version->getTitle(),
            'url' => $version->getUrl(),
            'force' => (int)$version->getforce(),
            'note' => $version->getNote()
        );
    }
}